#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

enum
{
    SocketErr = 2,
    BindErr,
    ListenErr,
    AcceptErr,
};

// TODO

Log lg;

class Sock
{
public:
    Sock()
    {
    }
    ~Sock()
    {
    }

public:
    void Socket()
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ < 0)
        {
            lg(Fatal, "socker error, %s: %d", strerror(errno), errno);
            exit(SocketErr);
        }
        lg(Info,"socket success,sockfd:%d\n",sockfd_);

        //服务器改掉，立刻重启，避免time_wait
        int opt = 1;
        setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        //INADDR_ANY表示全零，主机有多个IP地址时无论发送哪个都能接收
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(sockfd_, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, %s: %d", strerror(errno), errno);
            exit(BindErr);
        }
        lg(Info,"Bind success\n");
    }

    void Listen()
    {
        int n=listen(sockfd_,3);
        if(n<0)
        {
            lg(Fatal, "Listen error, %s: %d", strerror(errno), errno);
            exit(ListenErr);
        }
        lg(Info,"listen success,n:%d\n",n); 
    }

    int Accept()
    {
        struct sockaddr_in client;
        socklen_t len=sizeof(client);
        int fd=accept(sockfd_,(struct sockaddr*)&client,&len);
        if(fd==-1)
        {
            lg(Fatal,"accept error,%s:%d",strerror(errno),errno);
            exit(AcceptErr);
        }

        return fd;
    }

    int Listenfd()
    {
        return sockfd_;
    }

    void Close()
    {
        close(sockfd_);
    }

private:
    int sockfd_;
};